# 1 payload preprocessing
# task_payload_format-> algo_api_payload_format
import re
from django.http import response
import requests as rq
import uuid # 生成随机数


class Planner:

    def __init__(self, algo_type: str, num_beam: int, select_container: dict) -> None:
        self.algo_type = algo_type
        self.num_beam = num_beam
        self.select_container = select_container

    # __ 表示保护机制，私有化
    # 前处理格式转化 - >
    def __translate_input(self,input_dataset: list):
        res_list = []
        for cargo in input_dataset:
            temp = {
                "item": {
                    "id": str(uuid.uuid4()).split('-')[0],
                    "source_id": "",
                    "group": "",
                    "dimension": [
                        # 强制类型转化
                        float(cargo['height']),
                        float(cargo['width']),
                        float(cargo['height'])
                    ],
                    "weight": 0,
                    "load_bearing_capacity": 0,
                    "orientations": [
                        0,
                        1,
                        2,
                        3,
                        4,
                        5
                    ],
                    "number": int(cargo['quantity']),
                    "layer_limitation": 0
                },
                "product": {
                    "type": "default",
                    "art": cargo['name'],
                    "bearing_weight": 0,
                    "dest_port": "default"
                }
            }
            res_list.append(temp)
        return res_list

    # 后处理格式转化 转化结果

    def __translate_plans(self, result_payload: dict) -> dict:
        return dict(viewModelNames='any', **result_payload['response'])

    def compute(self, input_dataset):
        payload = {
            'request': {
                'config': {
                    'alog_type': self.algo_type,
                    'planner': {'num_beams': self.num_beams}
                },
                'container': self.selected_container,
                # 通过__translate_input 格式转化 前处理格式转化
                'items': self.__translate_input(input_dataset)
            }
        }
        response = rq.post(
            'https://lite.doraclp.cn/api/v2/plan/', json=payload)
        result_payload = response.json()
        # 后处理格式转化
        return self.__translate_plans(result_payload)
